<template>
	<view class="page">
		<!-- 统计卡片 -->
		<view class="stats-card">
			<view class="stat-item">
				<text class="stat-number">{{ stats.totalCount }}</text>
				<text class="stat-label">总审批</text>
			</view>
			<view class="stat-divider"></view>
			<view class="stat-item">
				<text class="stat-number">{{ stats.approvedCount }}</text>
				<text class="stat-label">已通过</text>
			</view>
			<view class="stat-divider"></view>
			<view class="stat-item">
				<text class="stat-number">{{ stats.rejectedCount }}</text>
				<text class="stat-label">已驳回</text>
			</view>
		</view>
		
		<!-- 筛选器 -->
		<view class="filter-section">
			<view class="filter-tabs">
				<view 
					class="filter-tab" 
					:class="{ active: currentFilter === 'all' }"
					@click="setFilter('all')"
				>
					全部
				</view>
				<view 
					class="filter-tab" 
					:class="{ active: currentFilter === 'approved' }"
					@click="setFilter('approved')"
				>
					已通过
				</view>
				<view 
					class="filter-tab" 
					:class="{ active: currentFilter === 'rejected' }"
					@click="setFilter('rejected')"
				>
					已驳回
				</view>
			</view>
		</view>
		
		<!-- 历史列表 -->
		<view class="history-list">
			<view 
				class="history-item" 
				v-for="item in filteredHistoryList" 
				:key="item.id"
			>
				<view class="item-header">
					<view class="type-tag" :class="'type-' + item.type">
						{{ item.typeName }}
					</view>
					<view class="status-tag" :class="'status-' + item.status">
						{{ getStatusText(item.status) }}
					</view>
				</view>
				
				<view class="item-content">
					<text class="title">{{ item.title }}</text>
					<text class="desc">{{ item.description }}</text>
					<view class="item-meta" v-if="item.applicant">
						<text class="meta-label">申请人：</text>
						<text class="meta-value">{{ item.applicant }}</text>
					</view>
					<view class="item-meta" v-if="item.approvalComment">
						<text class="meta-label">审批意见：</text>
						<text class="meta-value approval-comment">{{ item.approvalComment }}</text>
					</view>
				</view>
				
				<view class="item-footer">
					<text class="time">{{ item.endTime }}</text>
					<text class="approver">审批人：{{ item.assignee }}</text>
				</view>
			</view>
			
			<!-- 空状态 -->
			<view class="empty" v-if="filteredHistoryList.length === 0 && !loading">
				<uni-icons type="info" size="60" color="#ccc"></uni-icons>
				<text class="empty-text">暂无审批历史</text>
			</view>
			
			<!-- 加载状态 -->
			<view class="loading" v-if="loading">
				<uni-icons type="spinner-cycle" size="40" color="#999"></uni-icons>
				<text class="loading-text">加载中...</text>
			</view>
		</view>
	</view>
</template>

<script>
import { queryCompletedTasks, getApprovalStatistics } from '@/api/approval.js'
import { getUserInfo } from '@/utils/auth.js'

export default {
	data() {
		return {
			historyList: [],
			loading: false,
			userInfo: {},
			currentFilter: 'all',
			stats: {
				totalCount: 0,
				approvedCount: 0,
				rejectedCount: 0
			}
		}
	},
	computed: {
		// 过滤后的历史列表
		filteredHistoryList() {
			if (this.currentFilter === 'all') {
				return this.historyList
			} else if (this.currentFilter === 'approved') {
				return this.historyList.filter(item => 
					item.approvalStatus === '通过' || item.status === 'approved'
				)
			} else if (this.currentFilter === 'rejected') {
				return this.historyList.filter(item => 
					item.approvalStatus === '驳回' || item.status === 'rejected'
				)
			}
			return this.historyList
		}
	},
	onLoad() {
		this.userInfo = getUserInfo() || {}
		this.loadHistoryData()
	},
	onShow() {
		// 页面显示时刷新数据
		if (this.userInfo.username) {
			this.loadHistoryData()
		}
	},
	onPullDownRefresh() {
		// 下拉刷新
		this.loadHistoryData().finally(() => {
			uni.stopPullDownRefresh()
		})
	},
	methods: {
		// 返回上一页
		goBack() {
			uni.navigateBack()
		},
		
		// 设置筛选器
		setFilter(filter) {
			this.currentFilter = filter
		},
		
		// 加载历史数据
		async loadHistoryData() {
			if (this.loading) return
			
			this.loading = true
			this.historyList = []
			
			try {
				// 检查用户信息
				if (!this.userInfo.username) {
					uni.showToast({
						title: '用户信息异常，请重新登录',
						icon: 'none'
					})
					setTimeout(() => {
						uni.navigateTo({ url: '/pages/login/login' })
					}, 1500)
					return
				}

				// 并行获取已完成任务和统计数据
				const [completedRes, statsRes] = await Promise.all([
					queryCompletedTasks(this.userInfo.username),
					getApprovalStatistics(this.userInfo.username)
				])
				
				// 处理已完成任务数据
				if (completedRes.code === 200) {
					const completedTasks = completedRes.data || []
					
					// 格式化数据 - 根据实际API返回的数据结构进行适配
					this.historyList = completedTasks.map(item => {
						// 根据approvalStatus确定状态
						let status = 'completed'
						if (item.approvalStatus === '通过') {
							status = 'approved'
						} else if (item.approvalStatus === '驳回') {
							status = 'rejected'
						}
						
						return {
							...item,
							id: item.taskId || item.processInstanceId,
							taskId: item.taskId,
							title: item.taskName || '审批申请',
							description: '审批流程已完成',
							createTime: this.formatTime(item.startTime),
							endTime: this.formatTime(item.endTime),
							typeName: this.getTypeNameByTaskName(item.taskName),
							type: this.getApprovalTypeByTaskName(item.taskName),
							status: status,
							assignee: item.assignee || '系统用户',
							applicant: item.assignee || '系统用户',
							approvalStatus: item.approvalStatus || '未知',
							approvalComment: item.approvalComment || ''
						}
					})
					
					console.log('审批历史数据:', this.historyList)
					console.log('原始API数据:', completedTasks)
				} else {
					console.error('获取历史数据失败:', completedRes)
					uni.showToast({
						title: completedRes.message || '获取历史数据失败',
						icon: 'none'
					})
				}
				
				// 处理统计数据
				if (statsRes.code === 200) {
					const statsData = statsRes.data || {}
					this.stats = {
						totalCount: statsData.totalCount || this.historyList.length,
						approvedCount: statsData.approvedCount || 0,
						rejectedCount: statsData.rejectedCount || 0
					}
					console.log('审批统计数据:', this.stats)
				} else {
					// 如果统计接口失败，使用本地计算
					this.calculateStats()
				}
				
			} catch (error) {
				console.error('加载历史数据失败:', error)
				uni.showToast({
					title: '网络错误，请重试',
					icon: 'none'
				})
			} finally {
				this.loading = false
			}
		},
		
		// 计算统计数据
		calculateStats() {
			this.stats.totalCount = this.historyList.length
			this.stats.approvedCount = this.historyList.filter(item => 
				item.approvalStatus === '通过' || item.status === 'approved'
			).length
			this.stats.rejectedCount = this.historyList.filter(item => 
				item.approvalStatus === '驳回' || item.status === 'rejected'
			).length
		},
		
		// 获取状态文本
		getStatusText(status) {
			const statusMap = {
				approved: '已通过',
				completed: '已完成',
				rejected: '已驳回',
				cancelled: '已取消'
			}
			return statusMap[status] || status
		},
		
		// 根据任务状态获取状态
		getStatusFromTaskStatus(taskStatus) {
			if (taskStatus === 'completed' || taskStatus === 'approved') {
				return 'approved'
			} else if (taskStatus === 'rejected' || taskStatus === 'cancelled') {
				return 'rejected'
			}
			return taskStatus
		},
		
		// 获取类型名称
		getTypeName(processDefinitionKey) {
			const typeMap = {
				'leaveProcess': '请假申请',
				'expenseProcess': '费用报销',
				'purchaseProcess': '采购申请',
				'contractProcess': '合同审批',
				'complaintProcess': '投诉申请'
			}
			return typeMap[processDefinitionKey] || '审批流程'
		},
		
		// 根据流程定义Key获取审批类型
		getApprovalTypeByProcDefKey(processDefinitionKey) {
			if (!processDefinitionKey) return 'other'
			
			switch (processDefinitionKey) {
				case 'complaintProcess':
					return 'complaint'
				case 'customerProcess':
				case 'existingCustomerProcess':
				case 'distributorCustomerProcess':
					return 'new'
				case 'newCustomerProcess':
				case 'newCustomerApprovalProcess':
					return 'new'
				case 'returnProcess':
					return 'return'
				default:
					return 'other'
			}
		},
		
		// 根据任务名称获取类型名称
		getTypeNameByTaskName(taskName) {
			if (!taskName) return '其他'
			
			if (taskName.includes('请假')) return '请假申请'
			if (taskName.includes('报销')) return '费用报销'
			if (taskName.includes('采购')) return '采购申请'
			if (taskName.includes('投诉')) return '投诉处理'
			if (taskName.includes('申请')) return '审批申请'
			
			return '审批申请'
		},
		
		// 根据任务名称获取审批类型
		getApprovalTypeByTaskName(taskName) {
			if (!taskName) return 'other'
			
			if (taskName.includes('请假')) return 'leave'
			if (taskName.includes('报销')) return 'expense'
			if (taskName.includes('采购')) return 'purchase'
			if (taskName.includes('投诉')) return 'complaint'
			
			return 'other'
		},
		
		// 格式化时间
		formatTime(timeStr) {
			if (!timeStr) return ''
			const date = new Date(timeStr)
			const now = new Date()
			const diff = now - date
			
			// 如果是今天
			if (diff < 24 * 60 * 60 * 1000 && date.getDate() === now.getDate()) {
				return date.toLocaleTimeString('zh-CN', { 
					hour: '2-digit', 
					minute: '2-digit' 
				})
			}
			
			// 如果是昨天
			const yesterday = new Date(now)
			yesterday.setDate(yesterday.getDate() - 1)
			if (date.getDate() === yesterday.getDate()) {
				return '昨天 ' + date.toLocaleTimeString('zh-CN', { 
					hour: '2-digit', 
					minute: '2-digit' 
				})
			}
			
			// 其他情况显示完整日期
			return date.toLocaleString('zh-CN', {
				month: '2-digit',
				day: '2-digit',
				hour: '2-digit',
				minute: '2-digit'
			})
		},
		
	}
}
</script>

<style scoped>
.page {
	min-height: 100vh;
	background: #f5f7fa;
}

/* 页面头部 */
.page-header {
	display: flex;
	align-items: center;
	justify-content: space-between;
	padding: 20rpx 30rpx;
	background: #ffffff;
	border-bottom: 1rpx solid #f0f0f0;
}

.header-left, .header-right {
	width: 60rpx;
	height: 60rpx;
	display: flex;
	align-items: center;
	justify-content: center;
}

.header-left:active {
	background: #f5f5f5;
	border-radius: 30rpx;
}

.page-title {
	font-size: 32rpx;
	font-weight: bold;
	color: #333333;
}

/* 统计卡片 */
.stats-card {
	display: flex;
	align-items: center;
	background: #ffffff;
	margin: 20rpx 30rpx;
	padding: 30rpx;
	border-radius: 16rpx;
	box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.05);
}

.stat-item {
	display: flex;
	flex-direction: column;
	align-items: center;
	flex: 1;
}

.stat-number {
	font-size: 36rpx;
	font-weight: bold;
	color: #333333;
	margin-bottom: 8rpx;
}

.stat-label {
	font-size: 24rpx;
	color: #666666;
}

.stat-divider {
	width: 1rpx;
	height: 60rpx;
	background: #f0f0f0;
	margin: 0 20rpx;
}

/* 筛选器 */
.filter-section {
	background: #ffffff;
	margin: 0 30rpx 20rpx;
	border-radius: 16rpx;
	overflow: hidden;
}

.filter-tabs {
	display: flex;
}

.filter-tab {
	flex: 1;
	text-align: center;
	padding: 30rpx 0;
	font-size: 28rpx;
	color: #666666;
	position: relative;
}

.filter-tab.active {
	color: #667eea;
	font-weight: bold;
}

.filter-tab.active::after {
	content: '';
	position: absolute;
	bottom: 0;
	left: 50%;
	transform: translateX(-50%);
	width: 60rpx;
	height: 4rpx;
	background: #667eea;
	border-radius: 2rpx;
}

/* 历史列表 */
.history-list {
	padding: 0 30rpx;
}

.history-item {
	background: #ffffff;
	border-radius: 16rpx;
	padding: 30rpx;
	margin-bottom: 20rpx;
	box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.05);
}

.history-item:active {
	opacity: 0.8;
}

.item-header {
	display: flex;
	align-items: center;
	justify-content: space-between;
	margin-bottom: 15rpx;
}

.type-tag {
	padding: 8rpx 16rpx;
	border-radius: 6rpx;
	font-size: 22rpx;
	color: #ffffff;
}

.type-complaint {
	background: #ff6b6b;
}

.type-new {
	background: #667eea;
}

.type-return {
	background: #ffa502;
}

.type-other {
	background: #999999;
}

.status-tag {
	padding: 6rpx 16rpx;
	border-radius: 20rpx;
	font-size: 22rpx;
}

.status-approved {
	background: #e8f5e9;
	color: #4caf50;
}

.status-rejected {
	background: #ffebee;
	color: #f44336;
}

.item-content {
	margin-bottom: 15rpx;
}

.title {
	font-size: 28rpx;
	color: #333333;
	font-weight: 500;
	display: block;
	margin-bottom: 10rpx;
}

.desc {
	font-size: 24rpx;
	color: #666666;
	display: block;
	line-height: 1.4;
	margin-bottom: 10rpx;
}

.item-meta {
	display: flex;
	align-items: center;
	margin-top: 8rpx;
}

.meta-label {
	font-size: 22rpx;
	color: #999999;
	margin-right: 8rpx;
}

.meta-value {
	font-size: 22rpx;
	color: #666666;
}

.approval-comment {
	color: #333333;
	font-weight: 500;
	line-height: 1.4;
}

.item-footer {
	display: flex;
	align-items: center;
	justify-content: space-between;
}

.time {
	font-size: 24rpx;
	color: #999999;
}

.approver {
	font-size: 24rpx;
	color: #666666;
}

/* 空状态 */
.empty {
	padding: 120rpx 0;
	text-align: center;
	display: flex;
	flex-direction: column;
	align-items: center;
}

.empty-text {
	font-size: 28rpx;
	color: #999999;
	margin-top: 20rpx;
}

/* 加载状态 */
.loading {
	padding: 80rpx 0;
	text-align: center;
	display: flex;
	flex-direction: column;
	align-items: center;
}

.loading-text {
	font-size: 26rpx;
	color: #999999;
	margin-top: 20rpx;
}
</style>
